package com.lancer.dynamic.thread.pool;

import com.lancer.dynamic.thread.pool.lancerenum.RejectEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class LancerExecutor extends ThreadPoolExecutor {

    private String poolName;

    private RejectEnum rejectEnum;

    public String getPoolName() {
        return poolName;
    }

    public void setPoolName(String poolName) {
        this.poolName = poolName;
    }


    public RejectEnum getRejectEnum() {
        return rejectEnum;
    }

    public void setRejectEnum(RejectEnum rejectEnum) {
        this.rejectEnum = rejectEnum;
    }

    public LancerExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          RejectEnum rejectEnum, String poolName) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, switch (rejectEnum) {
            case CALLER_RUNS -> new ThreadPoolExecutor.CallerRunsPolicy();
            case DISCARD -> new ThreadPoolExecutor.DiscardPolicy();
            case DISCARD_OLDEST -> new ThreadPoolExecutor.DiscardOldestPolicy();
            default -> new ThreadPoolExecutor.AbortPolicy();
        });
        this.poolName = poolName;
        this.rejectEnum = rejectEnum;
    }

    // 线程安全的更新方法
    public synchronized void updateRejectedPolicy(RejectEnum rejectEnum) {
        this.rejectEnum = rejectEnum;
        RejectedExecutionHandler handler = switch (rejectEnum) {
            case CALLER_RUNS -> new ThreadPoolExecutor.CallerRunsPolicy();
            case DISCARD -> new ThreadPoolExecutor.DiscardPolicy();
            case DISCARD_OLDEST -> new ThreadPoolExecutor.DiscardOldestPolicy();
            default -> new ThreadPoolExecutor.AbortPolicy();
        };
        setRejectedExecutionHandler(handler);
        log.info("拒绝策略已更新为: " + handler.getClass().getSimpleName());
    }

    // 使用示例
    public static void main(String[] args) {
        LancerExecutor pool = new LancerExecutor(
                5, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100),
                RejectEnum.CALLER_RUNS, "testool"
        );

        // 动态更新拒绝策略
        pool.updateRejectedPolicy(RejectEnum.CALLER_RUNS);
        RejectedExecutionHandler rejectedExecutionHandler = pool.getRejectedExecutionHandler();
        log.info("拒绝策略已更新为: " + rejectedExecutionHandler.getClass().getSimpleName());
    }
}
